import axios, {AxiosResponse} from "axios";
import {message} from "antd";
import Cookies from 'js-cookie'

export const BASE_URL = process.env.REACT_APP_BASE_URL;
// 文件上传地址
export const BASE_UPLOAD_FILE = "/api/common/upload"
// 重新配置axios
const instance = axios.create({
    baseURL: "/api/back"
});


const token = Cookies.get("token");

// 配置请求拦截器
instance.interceptors.request.use(async (config) => {
    // 是否为登录请求
    if ((config.url ?? '').indexOf("login") < 0) {
        if (token) {
            config.headers['token'] = token;
        } else {
            await message.error("token过期");
            // 返回登录页面
            window.location.replace("/");
        }
    }
    return config;
});

// 配置响应拦截器
instance.interceptors.response.use(async (res: AxiosResponse) => {
    const {code, msg} = res.data.data;
    if (msg === "token过期") {
        setTimeout(() => window.location.href = "/", 1000)
    }
    if (code > 201) {
        await Promise.reject(msg)
    }
    return res
}, async (err) => {
    const {code, msg} = err.response.data.data;
    if (code > 201) {
        await Promise.reject(msg)
    }
})

export default instance
